<template>
  <div class="orders-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <a-row :gutter="24" align="middle">
        <a-col flex="1">
          <h2>订单管理</h2>
          <p class="page-description">管理您的购买和销售订单</p>
        </a-col>
        <a-col>
          <a-space>
            <a-button @click="loadOrders">
              <template #icon
                ><IconifyIcon icon="ant-design:reload-outlined"
              /></template>
              刷新
            </a-button>
            <a-button type="primary" @click="showCreateOrderModal = true">
              <template #icon
                ><IconifyIcon icon="ant-design:plus-outlined"
              /></template>
              创建订单
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>

    <!-- 订单状态统计 -->
    <a-row :gutter="16" class="stats-row">
      <a-col :span="6">
        <a-card size="small">
          <a-statistic
            title="待支付"
            :value="orderStats.pending_payment"
            :value-style="{ color: '#faad14' }"
          >
            <template #prefix
              ><IconifyIcon icon="ant-design:clock-circle-outlined"
            /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card size="small">
          <a-statistic
            title="进行中"
            :value="orderStats.in_progress"
            :value-style="{ color: '#1890ff' }"
          >
            <template #prefix><LoadingOutlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card size="small">
          <a-statistic
            title="已完成"
            :value="orderStats.completed"
            :value-style="{ color: '#52c41a' }"
          >
            <template #prefix
              ><IconifyIcon icon="ant-design:check-circle-outlined"
            /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card size="small">
          <a-statistic
            title="已取消"
            :value="orderStats.cancelled"
            :value-style="{ color: '#f5222d' }"
          >
            <template #prefix
              ><IconifyIcon icon="ant-design:close-circle-outlined"
            /></template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 搜索和筛选 -->
    <a-card class="search-card" size="small">
      <a-form :model="searchForm" layout="inline" @finish="handleSearch">
        <a-form-item label="订单号" name="keyword">
          <a-input
            v-model="searchForm.keyword"
            placeholder="输入订单号或商品名称"
            allow-clear
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item label="订单状态" name="status">
          <a-select
            v-model="searchForm.status"
            placeholder="选择状态"
            allow-clear
            style="width: 150px"
          >
            <a-select-option value="pending_payment">待支付</a-select-option>
            <a-select-option value="paid">已支付</a-select-option>
            <a-select-option value="in_progress">进行中</a-select-option>
            <a-select-option value="completed">已完成</a-select-option>
            <a-select-option value="cancelled">已取消</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="角色" name="role">
          <a-select
            v-model="searchForm.role"
            placeholder="选择角色"
            allow-clear
            style="width: 120px"
          >
            <a-select-option value="buyer">买家</a-select-option>
            <a-select-option value="seller">卖家</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="日期范围" name="dateRange">
          <a-range-picker v-model="searchForm.dateRange" style="width: 240px" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">
            <template #icon
              ><IconifyIcon icon="ant-design:search-outlined"
            /></template>
            搜索
          </a-button>
        </a-form-item>
        <a-form-item>
          <a-button @click="resetSearch">重置</a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 订单列表 -->
    <a-card size="small">
      <a-table
        :columns="columns"
        :data-source="orders"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'listing'">
            <div class="listing-info">
              <a-space>
                <a-avatar
                  :size="40"
                  :src="record.listingImage || '/images/placeholder.jpg'"
                  shape="square"
                />
                <div>
                  <div class="listing-title">{{ record.listingTitle }}</div>
                  <div class="order-id">订单号: {{ record.id }}</div>
                </div>
              </a-space>
            </div>
          </template>

          <template v-else-if="column.key === 'buyer'">
            <div class="user-info">
              <a-space>
                <a-avatar :size="32" :src="record.buyer.avatar" />
                <div>
                  <div>{{ record.buyer.name }}</div>
                  <div class="contact-info">{{ record.buyer.phone }}</div>
                </div>
              </a-space>
            </div>
          </template>

          <template v-else-if="column.key === 'seller'">
            <div class="user-info">
              <a-space>
                <a-avatar :size="32" :src="record.seller.avatar" />
                <div>
                  <div>{{ record.seller.name }}</div>
                  <div class="contact-info">{{ record.seller.phone }}</div>
                </div>
              </a-space>
            </div>
          </template>

          <template v-else-if="column.key === 'amount'">
            <div class="amount-info">
              <div class="total-amount">
                ¥{{ formatPrice(record.totalAmount) }}
              </div>
              <div class="price-detail">
                单价: ¥{{ formatPrice(record.price.finalPrice) }}/{{
                  record.price.unit
                }}
              </div>
              <div v-if="record.quantity > 1" class="quantity-info">
                数量: {{ record.quantity }}
              </div>
            </div>
          </template>

          <template v-else-if="column.key === 'duration'">
            <div class="duration-info">
              <div>{{ formatDate(record.duration.startDate) }}</div>
              <div>至</div>
              <div>{{ formatDate(record.duration.endDate) }}</div>
              <div class="duration-length">
                {{
                  record.duration.months
                    ? `${record.duration.months}个月`
                    : `${record.duration.nights}晚`
                }}
              </div>
            </div>
          </template>

          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ record.statusName }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'payment'">
            <div class="payment-info">
              <div v-if="record.payment.method">
                <a-tag size="small">{{
                  getPaymentMethodName(record.payment.method)
                }}</a-tag>
              </div>
              <div class="payment-amount">
                已付: ¥{{ formatPrice(record.payment.paidAmount) }}
              </div>
              <div v-if="record.balance > 0" class="balance-info">
                余款: ¥{{ formatPrice(record.balance) }}
              </div>
            </div>
          </template>

          <template v-else-if="column.key === 'actions'">
            <a-space>
              <a-button size="small" @click="viewOrderDetail(record)">
                详情
              </a-button>
              <a-dropdown v-if="getOrderActions(record).length > 0">
                <a-button size="small"> 操作 <DownOutlined /> </a-button>
                <template #overlay>
                  <a-menu @click="handleOrderAction($event, record)">
                    <a-menu-item
                      v-for="action in getOrderActions(record)"
                      :key="action.key"
                      :disabled="action.disabled"
                    >
                      {{ action.label }}
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 创建订单弹窗 -->
    <a-modal
      v-model:visible="showCreateOrderModal"
      title="创建订单"
      width="800px"
      :footer="null"
    >
      <p>创建订单功能开发中...</p>
    </a-modal>

    <!-- 订单详情弹窗 -->
    <a-modal
      v-model:visible="showDetailModal"
      title="订单详情"
      width="900px"
      :footer="null"
    >
      <div v-if="selectedOrder" class="order-detail">
        <!-- 订单基本信息 -->
        <a-descriptions title="订单信息" :column="2" bordered size="small">
          <a-descriptions-item label="订单号">
            {{ selectedOrder.id }}
          </a-descriptions-item>
          <a-descriptions-item label="订单状态">
            <a-tag :color="getStatusColor(selectedOrder.status)">
              {{ selectedOrder.statusName }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ formatDateTime(selectedOrder.createdAt) }}
          </a-descriptions-item>
          <a-descriptions-item label="更新时间">
            {{ formatDateTime(selectedOrder.updatedAt) }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 商品信息 -->
        <a-descriptions
          title="商品信息"
          :column="1"
          bordered
          size="small"
          style="margin-top: 16px"
        >
          <a-descriptions-item label="商品名称">
            {{ selectedOrder.listingTitle }}
          </a-descriptions-item>
          <a-descriptions-item label="使用需求">
            {{ selectedOrder.requirements.usage }}
          </a-descriptions-item>
          <a-descriptions-item label="特殊要求">
            {{ selectedOrder.requirements.specialNeeds }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 交易双方 -->
        <a-row :gutter="16" style="margin-top: 16px">
          <a-col :span="12">
            <a-descriptions title="买家信息" :column="1" bordered size="small">
              <a-descriptions-item label="姓名">
                {{ selectedOrder.buyer.name }}
              </a-descriptions-item>
              <a-descriptions-item label="联系电话">
                {{ selectedOrder.buyer.phone }}
              </a-descriptions-item>
              <a-descriptions-item label="邮箱">
                {{ selectedOrder.buyer.email }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
          <a-col :span="12">
            <a-descriptions title="卖家信息" :column="1" bordered size="small">
              <a-descriptions-item label="名称">
                {{ selectedOrder.seller.name }}
              </a-descriptions-item>
              <a-descriptions-item label="联系电话">
                {{ selectedOrder.seller.phone }}
              </a-descriptions-item>
              <a-descriptions-item label="邮箱">
                {{ selectedOrder.seller.email }}
              </a-descriptions-item>
            </a-descriptions>
          </a-col>
        </a-row>

        <!-- 价格信息 -->
        <a-descriptions
          title="价格信息"
          :column="2"
          bordered
          size="small"
          style="margin-top: 16px"
        >
          <a-descriptions-item label="原价">
            ¥{{ formatPrice(selectedOrder.price.originalPrice) }}/{{
              selectedOrder.price.unit
            }}
          </a-descriptions-item>
          <a-descriptions-item label="成交价">
            ¥{{ formatPrice(selectedOrder.price.finalPrice) }}/{{
              selectedOrder.price.unit
            }}
          </a-descriptions-item>
          <a-descriptions-item label="数量">
            {{ selectedOrder.quantity }}
          </a-descriptions-item>
          <a-descriptions-item label="总金额">
            ¥{{ formatPrice(selectedOrder.totalAmount) }}
          </a-descriptions-item>
          <a-descriptions-item label="定金">
            ¥{{ formatPrice(selectedOrder.deposit) }}
          </a-descriptions-item>
          <a-descriptions-item label="余款">
            ¥{{ formatPrice(selectedOrder.balance) }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 支付信息 -->
        <a-descriptions
          title="支付信息"
          :column="2"
          bordered
          size="small"
          style="margin-top: 16px"
        >
          <a-descriptions-item label="支付方式">
            {{ getPaymentMethodName(selectedOrder.payment.method) }}
          </a-descriptions-item>
          <a-descriptions-item label="支付状态">
            <a-tag :color="getPaymentStatusColor(selectedOrder.payment.status)">
              {{ getPaymentStatusName(selectedOrder.payment.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="已支付金额">
            ¥{{ formatPrice(selectedOrder.payment.paidAmount) }}
          </a-descriptions-item>
          <a-descriptions-item label="支付时间">
            {{
              selectedOrder.payment.paidAt
                ? formatDateTime(selectedOrder.payment.paidAt)
                : formatDateTimeformatDateTime
            }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 备注信息 -->
        <div v-if="selectedOrder.notes" style="margin-top: 16px">
          <h4>备注信息</h4>
          <a-alert :message="selectedOrder.notes" type="info" />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import { getOrders } from '#/api/resource-center';

// 响应式数据
const loading = ref(false);
const showCreateOrderModal = ref(false);
const showDetailModal = ref(false);
const selectedOrder = ref(null);

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: undefined,
  role: undefined,
  dateRange: undefined,
});

// 订单列表
const orders = ref([]);

// 订单统计
const orderStats = computed(() => {
  const stats = {
    pending_payment: 0,
    paid: 0,
    in_progress: 0,
    completed: 0,
    cancelled: 0,
  };

  orders.value.forEach((order) => {
    if (stats[order.status] !== undefined) {
      stats[order.status]++;
    }
  });

  return stats;
});

// 表格列配置
const columns = [
  {
    title: '商品信息',
    key: 'listing',
    width: 280,
  },
  {
    title: '买家',
    key: 'buyer',
    width: 150,
  },
  {
    title: '卖家',
    key: 'seller',
    width: 150,
  },
  {
    title: '金额',
    key: 'amount',
    width: 140,
  },
  {
    title: '使用期间',
    key: 'duration',
    width: 160,
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
  },
  {
    title: '支付信息',
    key: 'payment',
    width: 140,
  },
  {
    title: '操作',
    key: 'actions',
    width: 120,
    fixed: 'right',
  },
];

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: number[]) =>
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
});

// 格式化价格
const formatPrice = (price: number) => {
  if (price >= 10000) {
    return (price / 10000).toFixed(1) + '万';
  }
  return price.toLocaleString();
};

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString();
};

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  return new Date(dateString).toLocaleString();
};

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap = {
    pending_payment: 'orange',
    paid: 'blue',
    in_progress: 'processing',
    completed: 'success',
    cancelled: 'error',
  };
  return colorMap[status] || 'default';
};

// 获取支付方式名称
const getPaymentMethodName = (method: string) => {
  const methodMap = {
    alipay: '支付宝',
    wechat_pay: '微信支付',
    bank_transfer: '银行转账',
    credit_card: '信用卡',
    '': '未选择',
  };
  return methodMap[method] || method;
};

// 获取支付状态颜色
const getPaymentStatusColor = (status: string) => {
  const colorMap = {
    pending: 'orange',
    partial: 'blue',
    completed: 'success',
    cancelled: 'error',
  };
  return colorMap[status] || 'default';
};

// 获取支付状态名称
const getPaymentStatusName = (status: string) => {
  const statusMap = {
    pending: '待支付',
    partial: '部分支付',
    completed: '已支付',
    cancelled: '已取消',
  };
  return statusMap[status] || status;
};

// 获取订单可用操作
const getOrderActions = (order: any) => {
  const actions = [];

  switch (order.status) {
    case 'pending_payment':
      actions.push(
        { key: 'pay', label: '立即支付' },
        { key: 'cancel', label: '取消订单' },
      );
      break;
    case 'paid':
      actions.push(
        { key: 'confirm', label: '确认服务' },
        { key: 'refund', label: '申请退款' },
      );
      break;
    case 'in_progress':
      actions.push(
        { key: 'complete', label: '完成订单' },
        { key: 'dispute', label: '申请仲裁' },
      );
      break;
    case 'completed':
      if (!order.rating) {
        actions.push({ key: 'rate', label: '评价' });
      }
      break;
  }

  return actions;
};

// 处理订单操作
const handleOrderAction = ({ key }: { key: string }, order: any) => {
  console.log('订单操作:', key, order.id);

  switch (key) {
    case 'pay':
      message.info('跳转到支付页面');
      break;
    case 'cancel':
      message.info('取消订单');
      break;
    case 'confirm':
      message.info('确认服务');
      break;
    case 'refund':
      message.info('申请退款');
      break;
    case 'complete':
      message.info('完成订单');
      break;
    case 'dispute':
      message.info('申请仲裁');
      break;
    case 'rate':
      message.info('评价订单');
      break;
  }
};

// 查看订单详情
const viewOrderDetail = (order: any) => {
  selectedOrder.value = order;
  showDetailModal.value = true;
};

// 加载订单列表
const loadOrders = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm,
      page: pagination.current,page,
      pageSize: pagination.pageSize,
    };

    // 处理日期范围
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      (params as any).startDate = searchForm.dateRange[0].format('YYYY-MM-DD');
      (params as any).endDate = searchForm.dateRange[1].format('YYYY-MM-DD');
    }

    const result = await getOrders(params);
    orders.value = result.items || [];
    pagination.total = result.total || 0;
  } catch (error) {
    console.error('获取订单列表失败:', error);
    message.error('获取订单列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  pagination.current = 1;
  loadOrders();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    keyword: '',
    status: undefined,
    role: undefined,
    dateRange: undefined,
  });
  pagination.current = 1;
  loadOrders();
};

// 表格变化处理
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadOrders();
};

// 初始化
onMounted(() => {
  loadOrders();
});
</script>

<style scoped>
.orders-page {
  padding: 16px;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.page-description {
  margin: 4px 0 0 0;
  color: #6b7280;
  font-size: 14px;
}

.stats-row {
  margin-bottom: 24px;
}

.search-card {
  margin-bottom: 16px;
}

.listing-info {
  display: flex;
  align-items: center;
}

.listing-title {
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 2px;
}

.order-id {
  font-size: 12px;
  color: #6b7280;
}

.user-info {
  display: flex;
  align-items: center;
}

.contact-info {
  font-size: 12px;
  color: #6b7280;
}

.amount-info {
  text-align: right;
}

.total-amount {
  font-size: 16px;
  font-weight: 600;
  color: #f5222d;
}

.price-detail {
  font-size: 12px;
  color: #6b7280;
  margin-top: 2px;
}

.quantity-info {
  font-size: 12px;
  color: #6b7280;
  margin-top: 2px;
}

.duration-info {
  font-size: 12px;
  text-align: center;
}

.duration-length {
  color: #6b7280;
  margin-top: 4px;
}

.payment-info {
  text-align: center;
}

.payment-amount {
  font-size: 12px;
  color: #52c41a;
  margin-top: 2px;
}

.balance-info {
  font-size: 12px;
  color: #fa8c16;
  margin-top: 2px;
}

.order-detail {
  max-height: 70vh;
  overflow-y: auto;
}
</style>
